import axios from "axios";
import { getToken } from "./storage";

const http = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? process.env.BASE_APP_BASE_URL : process.env.BASE_DEV_APP_BASE_URL, 
  timeout: 5000, // request timeout
});

http.defaults.headers.post["Content-Type"] = "application/json";

http.interceptors.request.use(
  (config) => {
    config.headers = {
      "Content-Type": "application/json",
    };
    config.headers["Authorization"] = getToken();
    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error.message);
  }
);

http.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      return Promise.reject(response.msg || "Error");
    } else {
      return response.data;
    }
  },
  (error) => {
    console.log('http.interceptors.response',error.message)
    return Promise.reject(error.message);
  }
);

const request = (options) => {
    return new Promise((resolve, reject) => {
        http(options)
            .then(response => {
                resolve(response);
            })
            .catch(error => {
                console.log('request',error)
                reject(error);
            });
    });
}

 const get = (url) => {
    return request({
        method: "GET",
        url
    });
}

 const post = (url, data) => {
    return request({
        method: "POST",
        url,
        data
    });
}

const Http = {
    get,
    post
}

export default Http;
